package storeSorting

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"insighttracking/apps/sorting/internal/svc"
	"insighttracking/apps/sorting/internal/types"
	"insighttracking/common/utils"
	"insighttracking/query/service"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type PrintLabelApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewPrintLabelApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *PrintLabelApiLogic {
	hostname, _ := os.Hostname()
	return &PrintLabelApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *PrintLabelApiLogic) PrintLabelApi(req *types.StoreSortingPrintLabelReq) (resp *types.StoreSortingPrintLabelResp, err error) {
	// 1.获取订单信息
	storeSortingDetail, err := service.StoreSortingDetailService.GetStoreSortingDetailByUuIdApi(l.ctx, req.UUID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("当前订单没有分拣数据1")
	}

	storeSorting, err := service.StoreSortingService.GetStoreSortingByIdApi(l.ctx, storeSortingDetail.StoreSortingID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("当前订单没有分拣数据2")
	}

	orderEntity, err := service.OrdersService.GetByIdApi(l.ctx, storeSorting.OrdersID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("当前订单没有分拣数据3")
	}
	spuMap, err := service.OrdersDetailService.GetTotalSpuApi(l.ctx, []int64{storeSorting.OrdersID})
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("当前订单没有分拣数据4")
	}

	customerName, _ := service.EnterpriseCustomerService.GetNameByIdApi(l.ctx, orderEntity.CustomerID)
	return &types.StoreSortingPrintLabelResp{
		OrderNo:           orderEntity.OrderNo,                                   // 订单流水号
		CustomerID:        orderEntity.CustomerID,                                // 客户id,关联到enterprise_customer表主键id
		CustomerName:      customerName,                                          // 客户id,关联到enterprise_customer表主键id
		TotalCount:        spuMap[storeSortingDetail.SpuID].Count.StringFixed(2), // 下单量
		SpuName:           storeSortingDetail.SnapshotSpuName,                    // 商品名称
		CategoryName:      storeSortingDetail.SnapshotCategory,                   // 商品分类
		Unit:              storeSortingDetail.SnapshotUnit,                       //单位
		StoreSortingCount: storeSortingDetail.OutboundCount.StringFixed(2),       // 分拣数量
		StoreSortingDate:  utils.TimestampToString(storeSortingDetail.CreatedAt), // 分拣时间
	}, nil
}
